package com.yitiao.spring.utils;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

/**
 * <h3>包扫描工具类</h3>
 * <p></p>
 */
@Slf4j
public class ClassUtil {
    public static final String FILE_PROTOCOL = "file";

    /**
     * 获取包名对应的编译后的class文件夹资源
     */
    public static Set<Class<?>> extractPackageClass(String packageName) {
        Set<Class<?>> classSet = new HashSet<>();
        // 通过类加载器获取资源(编译后的class文件)
        ClassLoader classLoader = getClassLoader();
        URL resource = classLoader.getResource(packageName.replace(".", "/"));
        if (resource == null) {
            log.warn("unable to retrieve anything from package: " + packageName);
            return classSet;
        }
        //过滤出文件类型的资源
        if (resource.getProtocol().equalsIgnoreCase(FILE_PROTOCOL)) {
            File packageDirectory = new File(resource.getPath());
            extractClassFile(classSet, packageDirectory, packageName);
        }
        return classSet;
    }

    /**
     * 递归获取目标package里面的所有class文件(包括子package里的class文件)
     */
    public static void extractClassFile(Set<Class<?>> classSet, File packageDirectory, String packageName) {
        if (!packageDirectory.isDirectory()) {
            return;
        }
        File[] files = packageDirectory.listFiles(new FileFilter() {
            @Override
            public boolean accept(File file) {
                // file 可能是文件或文件夹
                if (file.isDirectory()) {
                    // 将其留在文件夹内
                    return true;
                } else {
                    // 获取文件的绝对值路径
                    String absoluteFilePath = file.getAbsolutePath();
                    if (absoluteFilePath.endsWith(".class")) {
                        // 拼接出全路径类名 com.yitiao.entity.dto.MainPageInfoDTO
                        absoluteFilePath = absoluteFilePath.replace(File.separator, ".");
                        String className = absoluteFilePath.substring(absoluteFilePath.indexOf(packageName));
                        className = className.substring(0, className.lastIndexOf("."));  // 去除 .class 后缀
                        // 通过反射机制获取对应的Class对象并加入到classSet里
                        Class targetClass = loadClass(className);
                        classSet.add(targetClass);
                    }
                    // 从文件夹内过滤掉
                    return false;
                }
            }
        });
        if (files != null) {
            for (File f : files) {
                //递归调用
                extractClassFile(classSet, f, packageName);
            }
        }
    }

    @SneakyThrows
    private static Class loadClass(String className) {
        return Class.forName(className);
    }


    /**
     * 获取classLoader
     */
    public static ClassLoader getClassLoader() {
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * 实例化class
     *
     * @param clazz Class
     * @param <T>   class的类型
     * @param accessible   是否支持创建出私有class对象的实例
     * @return 类的实例化
     */
    public static <T> T newInstance(Class<?> clazz, boolean accessible){
        try {
            Constructor<?> constructor = clazz.getDeclaredConstructor();
            constructor.setAccessible(accessible);
            return (T)constructor.newInstance();
        } catch (Exception e) {
            log.error("newInstance error", e);
            throw new RuntimeException(e);
        }
    }

    public static void setField(Field field, Object targetBean, Object fieldValue, boolean accessible) {
        field.setAccessible(accessible);
        try {
            field.set(targetBean, fieldValue);
        } catch (IllegalAccessException e) {
            log.error("setField error", e);
            throw new RuntimeException(e);
        }
    }

//    public static void main(String[] args) {
//        extractPackageClass("com.yitiao.entity");
//    }

}
